package com.example.myapplication;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;

public class HistoryActivity extends AppCompatActivity {
    private ListView listViewHistory;
    private DatabaseHelper dbHelper;
    private Button btnAll, btnIncome, btnExpense;
    private TextView tvHeader;
    private int currentView = 0; // 0=明细, 1=收入分类, 2=支出分类
    private String currentCategory = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);

        dbHelper = new DatabaseHelper(this);
        listViewHistory = findViewById(R.id.listViewHistory);
        btnAll = findViewById(R.id.btnAll);
        btnIncome = findViewById(R.id.btnIncome);
        btnExpense = findViewById(R.id.btnExpense);
        tvHeader = findViewById(R.id.tvHeader);

        findViewById(R.id.btnBack).setOnClickListener(v -> finish());

        btnAll.setOnClickListener(v -> {
            currentView = 0;
            currentCategory = "";
            updateButtonStates();
            loadHistory();
        });

        btnIncome.setOnClickListener(v -> {
            currentView = 1;
            currentCategory = "";
            updateButtonStates();
            loadIncomeCategories();
        });

        btnExpense.setOnClickListener(v -> {
            currentView = 2;
            currentCategory = "";
            updateButtonStates();
            loadExpenseCategories();
        });

        // 列表项点击事件
        listViewHistory.setOnItemClickListener((parent, view, position, id) -> {
            if (currentView == 1) {
                // 点击收入分类项
                String category = ((TextView) view).getText().toString().split(":")[0];
                loadRecordsByIncomeCategory(category);
            } else if (currentView == 2) {
                // 点击支出分类项
                String category = ((TextView) view).getText().toString().split(":")[0];
                loadRecordsByExpenseCategory(category);
            }
        });

        // 初始加载
        updateButtonStates();
        loadHistory();
    }

    private void updateButtonStates() {
        btnAll.setBackgroundTintList(getResources().getColorStateList(
                currentView == 0 ? R.color.colorPrimary : R.color.grey));
        btnIncome.setBackgroundTintList(getResources().getColorStateList(
                currentView == 1 ? R.color.colorPrimary : R.color.grey));
        btnExpense.setBackgroundTintList(getResources().getColorStateList(
                currentView == 2 ? R.color.colorPrimary : R.color.grey));
    }

    private void loadHistory() {
        tvHeader.setText("历史记录");
        Cursor cursor = dbHelper.getAllRecords();
        List<String> records = new ArrayList<>();
        if (cursor != null && cursor.moveToFirst()) {
            do {
                records.add(formatRecord(cursor));
            } while (cursor.moveToNext());
            cursor.close();
        } else {
            records.add("暂无记录");
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, records);
        listViewHistory.setAdapter(adapter);
    }

    private void loadIncomeCategories() {
        tvHeader.setText("收入分类");
        Cursor cursor = dbHelper.getIncomeGroupedByCategory();
        List<String> categories = new ArrayList<>();
        if (cursor != null && cursor.moveToFirst()) {
            do {
                String category = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_INCOME_CATEGORY));
                double total = cursor.getDouble(cursor.getColumnIndex("total_income"));
                int count = cursor.getInt(cursor.getColumnIndex("count"));
                categories.add(category + ": ¥" + String.format("%.2f", total) + " (" + count + "笔)");
            } while (cursor.moveToNext());
            cursor.close();
        } else {
            categories.add("暂无收入记录");
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, categories);
        listViewHistory.setAdapter(adapter);
    }

    private void loadExpenseCategories() {
        tvHeader.setText("支出分类");
        Cursor cursor = dbHelper.getExpenseGroupedByCategory();
        List<String> categories = new ArrayList<>();
        if (cursor != null && cursor.moveToFirst()) {
            do {
                String category = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_WASTE_CATEGORY));
                double total = cursor.getDouble(cursor.getColumnIndex("total_expense"));
                int count = cursor.getInt(cursor.getColumnIndex("count"));
                categories.add(category + ": ¥" + String.format("%.2f", total) + " (" + count + "笔)");
            } while (cursor.moveToNext());
            cursor.close();
        } else {
            categories.add("暂无支出记录");
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, categories);
        listViewHistory.setAdapter(adapter);
    }

    private void loadRecordsByIncomeCategory(String category) {
        currentCategory = category;
        tvHeader.setText("收入: " + category);
        Cursor cursor = dbHelper.getRecordsByIncomeCategory(category);
        List<String> records = new ArrayList<>();
        if (cursor != null && cursor.moveToFirst()) {
            do {
                records.add(formatRecord(cursor));
            } while (cursor.moveToNext());
            cursor.close();
        } else {
            records.add("暂无记录");
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, records);
        listViewHistory.setAdapter(adapter);
    }

    private void loadRecordsByExpenseCategory(String category) {
        currentCategory = category;
        tvHeader.setText("支出: " + category);
        Cursor cursor = dbHelper.getRecordsByExpenseCategory(category);
        List<String> records = new ArrayList<>();
        if (cursor != null && cursor.moveToFirst()) {
            do {
                records.add(formatRecord(cursor));
            } while (cursor.moveToNext());
            cursor.close();
        } else {
            records.add("暂无记录");
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, records);
        listViewHistory.setAdapter(adapter);
    }

    private String formatRecord(Cursor cursor) {
        int dateIndex = cursor.getColumnIndex(DatabaseHelper.COLUMN_DATE);
        int incomeIndex = cursor.getColumnIndex(DatabaseHelper.COLUMN_INCOME);
        int incomeCatIndex = cursor.getColumnIndex(DatabaseHelper.COLUMN_INCOME_CATEGORY);
        int wasteIndex = cursor.getColumnIndex(DatabaseHelper.COLUMN_WASTE);
        int wasteCatIndex = cursor.getColumnIndex(DatabaseHelper.COLUMN_WASTE_CATEGORY);
        int balanceIndex = cursor.getColumnIndex(DatabaseHelper.COLUMN_BALANCE);

        if (dateIndex != -1 && balanceIndex != -1) {
            String date = cursor.getString(dateIndex);
            double income = cursor.getDouble(incomeIndex);
            String incomeCategory = cursor.getString(incomeCatIndex);
            double waste = cursor.getDouble(wasteIndex);
            String wasteCategory = cursor.getString(wasteCatIndex);
            double balance = cursor.getDouble(balanceIndex);

            StringBuilder recordBuilder = new StringBuilder();
            recordBuilder.append("日期: ").append(date).append("\n");

            if (income > 0) {
                recordBuilder.append("收入: ¥").append(String.format("%.2f", income))
                        .append(" (").append(incomeCategory).append(")\n");
            }

            if (waste > 0) {
                recordBuilder.append("支出: ¥").append(String.format("%.2f", waste))
                        .append(" (").append(wasteCategory).append(")\n");
            }

            recordBuilder.append("余额: ¥").append(String.format("%.2f", balance));

            return recordBuilder.toString();
        } else {
            return "数据错误";
        }
    }
}